package com.xgkj.diyiketang.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.task.GetUserDetailTask;
import com.xgkj.diyiketang.task.ZhiboActionTask;
import com.xgkj.diyiketang.util.LogUtils;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.WeixinShareUtil;
import com.xgkj.diyiketang.wxapi.WXEntryActivity;

public class ZhuanyunOrderActivity extends BaseActivity implements View.OnClickListener {
    private TextView jibie_suc,jibie_num,dangqianshenfen,dangqianminge,yaoqingjibie;
    private TextView back,title_bar;
    private int detailTaskId = -1;
    private Button yaoqing_btn;
    private EatShowUserInfo userInfo;
    private String type;
    private String vipcode;
    private String shenfen1 = "";
    private ImageView img_bg;
    private int vipCode = 0;
    private String z_yz_minge;
    private String z_zr_minge;
    private String z_ds_minge;
    private String z_xy_minge;
    private String p_yz_minge;
    private String p_zr_minge;
    private String p_ds_minge;
    private String p_xy_minge;
    private boolean zhuanyun_boolean;
    private String zhuanyun_yuanzhang;
    private String zhuanyun_zhuren;
    private String zhuanyun_daoshi;
    private String zhuanyun_xueyuan;
    private boolean parent_boolean;
    private String fumu_yuanzhang;
    private String fumu_zhuren;
    private String fumu_daoshi;
    private String fumu_xueyuan;
    private PopupWindow popWindow;
    private WeixinShareReceive mWeixinShareReceive;
    private String weixinsharetype;
    private String weixinuseropenid;
    private IWXAPI api;
    public static Tencent mTencent;
    private int doShareTaskId = -1;
    private byte[] weixinshareByte;
    private String share_path;
    private LinearLayout quanyixuzhi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhuanyun_order);
        mTencent = Tencent.createInstance(ProtocolConst.QQ_ID, this.getApplicationContext());
        api = WXAPIFactory.createWXAPI(mContext, ProtocolConst.APP_ID);
        initUI();
        initPopWindow();
        getUserDetail();
    }

    private void getUserDetail() {
        GetUserDetailTask task = new GetUserDetailTask();
        task.addListener(new MyListener(mContext));
        detailTaskId = getEatShowApp().getTaskManager().addTask(task);
    }
    class WeixinShareReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println(intent.getAction());
            weixinuseropenid = intent.getStringExtra(ProtocolConst.WEIXIN_OPENID);

            if (intent.getAction().equalsIgnoreCase(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION)) {
//                doShare();
            } else if (intent.getAction().equalsIgnoreCase(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION)) {
//                doShare();
            }
            if (mWeixinShareReceive != null) {
                unregisterReceiver(mWeixinShareReceive);
                mWeixinShareReceive = null;
            }
        }

    }
    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {

        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
//            doShare();
        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub

        }
    };


    private void shareToWeiXin(String shareUrl, boolean isTimeLine) {
        if (!api.isWXAppSupportAPI() || !api.isWXAppInstalled()) {
            Toast.makeText(mContext, R.string.need_weixin_app, Toast.LENGTH_SHORT).show();
            return;
        }

        if (mWeixinShareReceive != null) {
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = shareUrl;
        WXMediaMessage msg = new WXMediaMessage(webPage);
        //msg.title = ppntitle;
        if (isTimeLine) {
            msg.title = "第一课堂";
        } else {
            msg.title = "第一课堂";
        }
        msg.description = "第一课堂";
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.app_icon);
        weixinshareByte = WeixinShareUtil.bmpToByteArray(bmp, true);
        if (weixinshareByte != null && weixinshareByte.length != 0) {
            msg.thumbData = weixinshareByte;
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }
    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }
//    private void doShare() {
//        ZhiboActionTask doShareTask = new ZhiboActionTask(mVid, "0");
//        doShareTask.addListener(new MyListener(this));
//        doShareTaskId = getEatShowApp().getTaskManager().addTask(doShareTask);
//    }
    class MyListener extends ShowToastTaskEventListener {
        public MyListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (data!=null){
                userInfo = (EatShowUserInfo) data;
                if (userInfo !=null){
                    vipCode = userInfo.getVipCode();
                    share_path = "http://115.28.236.67:8096/classroom/shareVip.html?vipCode="+vipCode+"";
                    if (type.equals("yaoqing")){
                        title_bar.setText("邀请好友");
                        jibie_suc.setText(vipCode+"");
                        jibie_suc.setTextColor(getResources().getColor(R.color.white));
                        jibie_num.setText("您的账号邀请码，是专属于您个人的身份标识");
                        jibie_num.setTextColor(getResources().getColor(R.color.white));
                        jibie_num.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);
                    }else {
                        jibie_num.setText("邀请码："+vipCode);
                    }
                    if (userInfo.getList() != null && userInfo.getList().size() > 0) {
                        for (int i = 0; i < userInfo.getList().size(); i++) {
                            String xueyuan = userInfo.getList().get(i).xueyuan;
                            if (type.equals("zhuanyun")&&xueyuan.equals("3d9513eb1b674af98de226b315765e3f")) {
                                if (userInfo.getList().get(i).shenfen.equals("0")) {
                                    z_yz_minge = userInfo.getList().get(i).minge;
                                    dangqianshenfen.setText("您的当前身份为院长,您目前拥有"+z_yz_minge+"个超值观看券");
                                } else if (userInfo.getList().get(i).shenfen.equals("1")) {
                                    z_zr_minge = userInfo.getList().get(i).minge;
                                    dangqianshenfen.setText("您的当前身份为主任,您目前拥有"+z_zr_minge+"个超值观看券");
                                } else if (userInfo.getList().get(i).shenfen.equals("2")) {
                                    z_ds_minge = userInfo.getList().get(i).minge;
                                    dangqianshenfen.setText("您的当前身份为导师,您目前拥有"+z_ds_minge+"个超值观看券");

                                } else if (userInfo.getList().get(i).shenfen.equals("3")) {
                                    z_xy_minge = userInfo.getList().get(i).minge;
                                    dangqianshenfen.setText("您的当前身份为学员,您目前拥有"+z_xy_minge+"个超值观看券");

                                }
                                //父母大学
                            } else if (type.equals("parent")&&xueyuan.equals("2737f7a418bf41c998728e6a0f9f253d")) {
                                if (userInfo.getList().get(i).shenfen.equals("0")) {
                                    p_yz_minge = userInfo.getList().get(i).minge;
                                    dangqianshenfen.setText("您的当前身份为院长,您目前拥有"+p_yz_minge+"个超值观看券");

                                } else if (userInfo.getList().get(i).shenfen.equals("1")) {
                                    p_zr_minge = userInfo.getList().get(i).minge;
                                    dangqianshenfen.setText("您的当前身份为主任,您目前拥有"+p_zr_minge+"个超值观看券");

                                } else if (userInfo.getList().get(i).shenfen.equals("2")) {
                                    p_ds_minge = userInfo.getList().get(i).minge;
                                    dangqianshenfen.setText("您的当前身份为导师,您目前拥有"+p_ds_minge+"个超值观看券");

                                } else if (userInfo.getList().get(i).shenfen.equals("3")) {
                                    p_xy_minge = userInfo.getList().get(i).minge;
                                    dangqianshenfen.setText("您的当前身份为学员,您目前拥有"+p_xy_minge+"个超值观看券");

                                }
                            }
                        }
                    }
                    if (userInfo.getIdentityList() != null && userInfo.getIdentityList().size() > 0) {
                        for (int i = 0; i < userInfo.getIdentityList().size(); i++) {
                            String xueyuan = userInfo.getIdentityList().get(i).xueyuan;
                            //转运
                            if (type.equals("zhuanyun")&&xueyuan.equals("3d9513eb1b674af98de226b315765e3f")) {
                                String shenfen = userInfo.getIdentityList().get(i).shenfen;
                                zhuanyun_boolean = true;
                                if (shenfen.equals("0")) {
                                    zhuanyun_yuanzhang = "院长";
                                    jibie_suc.setText("您已成功购买院长");
                                } else if (shenfen.equals("1")) {
                                    zhuanyun_zhuren = "主任";
                                    jibie_suc.setText("您已成功购买主任");
                                } else if (shenfen.equals("2")) {
                                    zhuanyun_daoshi = "导师";
                                    jibie_suc.setText("您已成功购买导师");
                                } else if (shenfen.equals("3")) {
                                    zhuanyun_xueyuan = "学员";
                                    jibie_suc.setText("您已成功购买学员");
                                }
                                //父母大学
                            } else if (type.equals("parent")&&xueyuan.equals("2737f7a418bf41c998728e6a0f9f253d")) {
                                String shenfen = userInfo.getIdentityList().get(i).shenfen;
                                parent_boolean = true;
                                if (shenfen.equals("0")) {
                                    fumu_yuanzhang = "院长";
                                    jibie_suc.setText("您已成功购买院长");
                                } else if (shenfen.equals("1")) {
                                    fumu_zhuren = "主任";
                                    jibie_suc.setText("您已成功购买主任");
                                } else if (shenfen.equals("2")) {
                                    fumu_daoshi = "导师";
                                    jibie_suc.setText("您已成功购买导师");
                                } else if (shenfen.equals("3")) {
                                    fumu_xueyuan = "学员";
                                    jibie_suc.setText("您已成功购买学员");
                                }
                            }
                        }
                    }
                }
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    }

    private void initUI() {
        quanyixuzhi = (LinearLayout) findViewById(R.id.quanyixuzhi);
        dangqianshenfen = (TextView) findViewById(R.id.zhuanyun_order_jibie);
        yaoqingjibie = (TextView) findViewById(R.id.zhuanyun_yaoqing);
        yaoqing_btn = (Button) findViewById(R.id.live_prepare_btn);
        title_bar = (TextView) findViewById(R.id.title_bar);
        jibie_suc = (TextView) findViewById(R.id.jibie_suc);
        jibie_num = (TextView) findViewById(R.id.jibie_num);
        back = (TextView) findViewById(R.id.zhuanyun_back);
        img_bg = (ImageView) findViewById(R.id.shenfen_bg);
//        jibie_num.setText("邀请码："+vipCode);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        yaoqing_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
            }
        });
        if (getIntent().getExtras()!=null){
            type = getIntent().getExtras().getString("type");

            if (type.equals("zhuanyun")){
                title_bar.setText("转运学院");
                if (!TextUtils.isEmpty(getIntent().getExtras().getString("zhuanyun_yz"))){
                    shenfen1 = getIntent().getExtras().getString("zhuanyun_yz");
                }else if (!TextUtils.isEmpty(getIntent().getExtras().getString("zhuanyun_zr"))){
                    shenfen1 = getIntent().getExtras().getString("zhuanyun_zr");
                } else if (!TextUtils.isEmpty(getIntent().getExtras().getString("zhuanyun_ds"))){
                    shenfen1 = getIntent().getExtras().getString("zhuanyun_ds");
                } else if (!TextUtils.isEmpty(getIntent().getExtras().getString("zhuanyun_xy"))){
                    shenfen1 = getIntent().getExtras().getString("zhuanyun_xy");
                }
            }else if (type.equals("parent")){
                title_bar.setText("父母大学");
                if (!TextUtils.isEmpty(getIntent().getExtras().getString("zhuanyun_yz"))){
                    shenfen1 = getIntent().getExtras().getString("zhuanyun_yz");
                }else if (!TextUtils.isEmpty(getIntent().getExtras().getString("zhuanyun_zr"))){
                    shenfen1 = getIntent().getExtras().getString("zhuanyun_zr");
                } else if (!TextUtils.isEmpty(getIntent().getExtras().getString("zhuanyun_ds"))){
                    shenfen1 = getIntent().getExtras().getString("zhuanyun_ds");
                } else if (!TextUtils.isEmpty(getIntent().getExtras().getString("zhuanyun_xy"))){
                    shenfen1 = getIntent().getExtras().getString("zhuanyun_xy");
                }
            }else if (type.equals("yaoqing")){
                quanyixuzhi.setVisibility(View.GONE);
                img_bg.setBackgroundResource(R.drawable.guoxue_gm_x);
            }

        }
        if (shenfen1!=null&&shenfen1.equals("院长")){
            img_bg.setBackgroundResource(R.drawable.yz_x);
            jibie_suc.setText("您已成功购买院长");
        }else if (shenfen1!=null&&shenfen1.equals("主任")){
            img_bg.setBackgroundResource(R.drawable.zr_x);
            jibie_suc.setText("您已成功购买主任");
        } else if (shenfen1!=null&&shenfen1.equals("导师")){
            img_bg.setBackgroundResource(R.drawable.zr_x);
            jibie_suc.setText("您已成功购买导师");
        } else if (shenfen1!=null&&shenfen1.equals("学员")){
            img_bg.setBackgroundResource(R.drawable.zr_x);
            jibie_suc.setText("您已成功购买学员");
        }
//        share_path = "http://115.28.236.67:8096/classroom/live.html?vid=" + mVid + "";
    }
    private ImageView pengyouquan, wenxin, qq, weibo;
    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.share_pop, null);
        pengyouquan = ((ImageView) view.findViewById(R.id.share_to_timeline));
        pengyouquan.setOnClickListener(this);
        wenxin = ((ImageView) view.findViewById(R.id.share_to_weixinfriend));
        wenxin.setOnClickListener(this);
        weibo = ((ImageView) view.findViewById(R.id.share_to_weibo));
        weibo.setOnClickListener(this);
        qq = ((ImageView) view.findViewById(R.id.share_to_qq));
        qq.setOnClickListener(this);
        popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.share_to_timeline:
                weixinsharetype = "sharefriends";
                shareToWeiXin(share_path, true);
                popWindow.dismiss();
                break;
            case R.id.share_to_weixinfriend:
                weixinsharetype = "sharefriend";
                shareToWeiXin(share_path, false);
                popWindow.dismiss();
                break;
            case R.id.share_to_weibo:
                break;
            case R.id.share_to_qq:
                final Bundle params = new Bundle();
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, "第一课堂");
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "第一课堂");
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, share_path);
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://www.chiboker.com/diyiketangImage/diyiketang_icon.png");
                // params.putByteArray(QQShare.SHARE_TO_QQ_IMAGE_URL,weixinshareByte);
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "第一课堂");
                mTencent.shareToQQ(this, params, qqShareListener);
                popWindow.dismiss();
                break;
        }
    }
}
